package com.bhf.security.filter;

import com.alibaba.fastjson.JSON;
import com.bhf.constant.ResultCodeEnum;
import com.bhf.utils.JwtTokenManager;
import com.bhf.utils.RestResultUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author pwq
 */
public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter  {

    private static final String AUTHORIZATION_HEADER = "Authorization";

    public JwtTokenManager jwtTokenManager;

    public JwtAuthenticationTokenFilter(AuthenticationManager authenticationManager,JwtTokenManager jwtTokenManager) {
        super(authenticationManager);
        this.jwtTokenManager = jwtTokenManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        try {
            String tokenHeader = request.getHeader(AUTHORIZATION_HEADER);
            if (StringUtils.isNotBlank(tokenHeader) && SecurityContextHolder.getContext().getAuthentication() == null) {
                UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) jwtTokenManager.getAuthentication(tokenHeader);
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            chain.doFilter(request, response);
        }catch (Exception e){
            try {
                this.resultResponse(response,e);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
    private void resultResponse(HttpServletResponse response,Exception e) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter out = response.getWriter();
        if (e instanceof ExpiredJwtException){
            out.write(JSON.toJSONString(RestResultUtils.buildResult(ResultCodeEnum.AUTHENTICATION_INFO_EXPIRED,e.getMessage())));
        }else {
            out.write(JSON.toJSONString(RestResultUtils.buildResult(ResultCodeEnum.AUTHENTICATION_INFO_ERROR,e.getMessage())));
        }
        out.flush();
        out.close();
    }
}
